<template>
    <div class="user-list-page">
        <el-card shadow="hover" class="user-list-card">
            <div class="user-list-toolbar">
                <el-input v-model="keyword" placeholder="搜索用户名" style="width: 200px" @keyup.enter="handleSearch" />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button type="primary" @click="handleAdd">新增用户</el-button>
            </div>
            <el-table :data="list" style="width: 100%" stripe border>
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="role" label="角色" />
                <el-table-column prop="user_type" label="用户类型">
                    <template #default="scope">
                        {{ (Array.isArray(categoryList) ? categoryList.find(c => c.id === scope.row.user_type)?.name : '') || scope.row.user_type || '' }}
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="地址" />
                <el-table-column prop="contact" label="联系方式" />
                <el-table-column prop="created_at" label="创建时间">
                    <template #default="scope">
                        {{ formatDate(scope.row.created_at) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.row)" class="action-btn">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)"
                            :disabled="scope.row.role === 'admin'" class="action-btn">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination :current-page="page" :page-size="pageSize" :page-sizes="[5, 10, 20, 50]" :total="total"
                layout="total, sizes, prev, pager, next" @current-change="handlePageChange"
                @size-change="handleSizeChange" style="margin-top: 16px; justify-content: flex-end;" />
        </el-card>
        <!-- 编辑/新增弹窗 -->
        <el-dialog v-model="dialogVisible" :title="editId ? '编辑用户' : '新增用户'" width="480px" class="user-dialog">
            <el-form :model="editForm" :rules="rules" ref="formRef" label-width="80px" class="user-form">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" :disabled="!!editId" />
                </el-form-item>
                <el-form-item label="密码" v-if="!editId" prop="password">
                    <el-input v-model="editForm.password" type="password" />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="editForm.role">
                        <el-option label="管理员" value="admin" />
                        <el-option label="普通用户" value="user" />
                    </el-select>
                </el-form-item>
                <el-form-item label="用户类型" prop="user_type">
                    <el-select v-model="editForm.user_type">
                        <el-option v-for="cat in categoryList" :key="cat.id" :label="cat.name" :value="cat.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="editForm.address" />
                </el-form-item>
                <el-form-item label="联系方式">
                    <el-input v-model="editForm.contact" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSave">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, createUser, updateUser, deleteUser } from '../api/user'
import type { UserListResponse } from '../api/user'
import { getCategoryList, type CategoryItem } from '../api/category'

const list = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const keyword = ref('')

const dialogVisible = ref(false)
const editForm = ref<any>({})
const editId = ref<number | null>(null)

const categoryList = ref<CategoryItem[]>([])

const formRef = ref()
const rules = reactive({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    role: [{ required: true, message: '请选择角色', trigger: 'change' }],
    user_type: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
})

const fetchCategory = async () => {
    const res = await getCategoryList()
    console.log('getCategoryList 返回值:', res)
    categoryList.value = Array.isArray(res.list) ? res.list : []
}

const fetchList = async () => {
    const res: UserListResponse = await getUserList({ page: page.value, pageSize: pageSize.value, keyword: keyword.value })
    list.value = res.list
    total.value = res.total
}

const handleSearch = () => {
    page.value = 1
    fetchList()
}

const handlePageChange = (val: number) => {
    page.value = val
    fetchList()
}

const handleSizeChange = (val: number) => {
    pageSize.value = val
    page.value = 1
    fetchList()
}

const handleAdd = () => {
    editId.value = null
    editForm.value = { role: 'user', user_type: categoryList.value[0]?.id }
    dialogVisible.value = true
}

const handleEdit = (row: any) => {
    editId.value = row.id
    editForm.value = { ...row, password: '' }
    dialogVisible.value = true
}

const handleSave = async () => {
    await formRef.value.validate(async (valid: boolean) => {
        if (!valid) return
        if (editId.value) {
            await updateUser(editId.value, editForm.value)
            ElMessage.success('修改成功')
        } else {
            await createUser(editForm.value)
            ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        page.value = 1
        fetchList()
    })
}

const handleDelete = (id: number) => {
    ElMessageBox.confirm('确定要删除该用户吗？', '提示', { type: 'warning' })
        .then(async () => {
            await deleteUser(id)
            ElMessage.success('删除成功')
            fetchList()
        })
}

function formatDate(val: string) {
    if (!val) return ''
    const d = new Date(val)
    return isNaN(d.getTime()) ? '' : d.toLocaleString()
}

fetchCategory()
fetchList()
</script>

<style scoped>
.user-list-page {
    padding: 24px;
    background: #fff;
    min-height: 0;
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
}

.user-list-card {
    width: 100%;
    max-width: 100%;
    margin: 0;
    border-radius: 10px;
    box-sizing: border-box;
}

.user-list-toolbar {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.action-btn {
    margin-right: 8px;
}

.user-dialog .el-dialog__body {
    padding: 32px 32px 12px 32px;
    border-radius: 16px;
    background: #f8fafc;
}

.user-dialog .el-dialog__header {
    border-radius: 16px 16px 0 0;
    background: #fff;
    font-size: 20px;
    font-weight: bold;
    padding-bottom: 8px;
}

.dialog-footer {
    display: flex;
    justify-content: center;
    gap: 16px;
    padding-bottom: 12px;
}

.user-form .el-form-item {
    margin-bottom: 22px;
}
</style>
